import logger from "@shared/logger/renderer-logger";
import { triplitToken } from "@shared/triplit/token";
import { useCallback, useEffect, useState } from "react";
import { initTriplitClient } from "./client";
import { SidebarProvider } from "./components/ui/base/sidebar";
import { CodeStyleProvider } from "./context/code-style-provider";
import { ThemeProvider } from "./context/theme-provider";
import { Routes } from "./routes";
import {
  cleanupIpcEventBridge,
  setupIpcEventBridge,
} from "./services/ipc-event-bridge";

const { triplitService } = window.service;

export function App() {
  const [isConnected, setIsConnected] = useState(false);

  const hideSplashScreen = useCallback(() => {
    const splash = document.getElementById("app-splash");
    const app = document.querySelector("app");

    if (splash && app) {
      app.classList.add("ready");

      // Dispatch app loaded event to clear emergency button timer
      window.dispatchEvent(new CustomEvent("appLoaded"));

      setTimeout(() => {
        splash.classList.add("curtain-up");
        setTimeout(() => {
          splash.remove();
        }, 600);
      }, 100);
    }
  }, []);

  useEffect(() => {
    const setupClient = async () => {
      const client = initTriplitClient();
      client.onConnectionStatusChange((status) => {
        logger.info("Connection status changed", {
          status,
          process: "renderer",
        });
        setIsConnected(status === "OPEN");
      });

      const serverUrl = await triplitService.getServerPort();

      client.updateServerUrl(`http://localhost:${serverUrl}`);
      await client.startSession(triplitToken);

      // Setup IPC event bridge
      setupIpcEventBridge();
    };

    setupClient();

    // Cleanup on unmount
    return () => {
      cleanupIpcEventBridge();
    };
  }, []);

  useEffect(() => {
    if (isConnected) {
      hideSplashScreen();
    }
  }, [isConnected, hideSplashScreen]);

  return (
    <ThemeProvider>
      <CodeStyleProvider>
        <SidebarProvider>
          <Routes />
        </SidebarProvider>
      </CodeStyleProvider>
    </ThemeProvider>
  );
}
